package mware_lib;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

class IOThread extends Thread {
  private int count = 0;
  private String message = null;
  private List<PrintJob> messageLog = new ArrayList<>();
  
  private void printOut() {
    List<PrintJob> jobs;
    synchronized(this) {
      jobs = messageLog;
      messageLog = new ArrayList<>();
      if (message != null) {
        jobs.add(new PrintJob(count, message));
        message = null;
      }
    }
    for(PrintJob j : jobs)
      System.out.println(j);
  }
  
  public void print(String o) {
    synchronized(this) {
      if (message == null) {
        message = o;
        count = 1;
      } else {
        if (message.equals(o)) {
          ++count;
        } else {
          messageLog.add(new PrintJob(count, message));
          message = o;
          count = 1;
        }
      }
    }
  }
  
  @Override
  public void run() {
    try {
      System.out.println("IO-Thread gestartet.");
      while(true) {
        sleep(500);
        printOut();
      }
    } catch (InterruptedException e) {
      System.out.println("IO-Thread beendet");
    }
  }     
}

class PrintJob {
  private int count;
  private String message;

  public PrintJob(int count, String message) {
    this.count = count;
    this.message = message;
  }

  @Override
  public String toString() {
    return count + "x " + message;
  }

  @Override
  public int hashCode() {
    int hash = 3;
    hash = 73 * hash + this.count;
    hash = 73 * hash + Objects.hashCode(this.message);
    return hash;
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final PrintJob other = (PrintJob) obj;
    if (this.count != other.count) {
      return false;
    }
    if (!Objects.equals(this.message, other.message)) {
      return false;
    }
    return true;
  }
  
  
  
}
